package com.chaowen.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import com.chaowen.config.Config;

public class SocketCreate {
	/**
	 * 连接服务器
	 * @throws InterruptedException
	 * @throws ExecutionException
	 * @throws TimeoutException
	 */
	public static ExecutorService executor = Executors.newSingleThreadExecutor();
	public static Socket createSocket() throws Exception {
		Future<Socket> future = executor.submit(new Callable<Socket>(){
			@Override
			public Socket call() throws Exception {
				System.out.println("ipaddress: "+Config.ipAddress+"   "+Config.socketPort);
				if(Config.ipAddress==null||Config.socketPort==0) {
					return null;
				}
				InetAddress serverAddr = InetAddress.getByName(Config.ipAddress);
				System.out.println("开始创建Socket啦。。。。");
				Socket socket = new Socket(serverAddr, Config.socketPort);
				System.out.println("创建的socket："+socket);
				return socket;
			}
		});
		return future.get(1500, TimeUnit.MILLISECONDS);
	}
	
	public static PrintWriter getWriter(Socket socket) throws IOException{
        OutputStream socketOut=socket.getOutputStream();
        return new PrintWriter(socketOut,true);
    }
	public static BufferedReader getReader(Socket socket) throws IOException{
        InputStream socketIn=socket.getInputStream();
        return new BufferedReader(new InputStreamReader(socketIn));
    }
}
